<script setup lang="ts">
import { ref } from 'vue'
import type { IOrderPageParam, IOrder, IOrderItem } from '@/types/order'
import { pageOrderAPI, aginDetailAPI, cancelOrderAPI, pageOrderStatusAPI } from '@/services/order'
import { useMemberStore, useReview, useCategory, useOrder } from '@/stores'
import RefundPanel from './components/RefundPanel.vue'
const { getUserInfo } = useMemberStore()
const { setReviewData } = useReview()
// 导入列表组件
import OrderList from './components/OrderList.vue'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { formatChineseJson, formateStr } from '@/utils/http'
import wucTab from '@/components/wuc-tab.vue'

const { getBuyMethodName, setBuyMethodActiveIndex } = useCategory()
const { addOrderData, getorderStatusTabs, orderStatusTabsName, orderStatusTabsClassName } =
  useOrder()
import type { IcartItem } from '@/types/cart'
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
// tabs 数据
const orderTabs = ref(getorderStatusTabs())

// 获取页面参数
const query = defineProps<{
  type: number
}>()

const activeIndex = ref(orderTabs.value.findIndex((v) => v.orderState === Number(query.type)))

const initParams: IOrderPageParam = {
  page: 1,
  limit: 10,
  userId: getUserInfo()?.id,
  orderStatus: Number(query.type),
}
const params = ref(initParams as IOrderPageParam)
const noMore = ref(false)
const orderList = ref<IOrder[]>([])
const total = ref(0)
const finish = ref(false)
onUnload(() => {
  uni.$off('emitUpdateReviewId', emitUpdateReviewId)
})
onLoad(async () => {
  uni.$on('emitUpdateReviewId', emitUpdateReviewId)
  triggered.value = true
  await request()
})

const submitRefund = () => {
  ;(popup.value as any)?.close()
}
const emitUpdateReviewId = (val: any) => {
  orderList.value = orderList.value.map((item: IOrder) => {
    if (item.id === val.orderId) {
      return { ...item, reviewId: val.reviewId }
    }
    return item
  })
}
const request = async () => {
  if (finish.value) {
    return
  }

  finish.value = true
  const res = await pageOrderAPI({
    ...params.value,
    orderStatus: params.value.orderStatus === -1 ? null : params.value.orderStatus,
  })
  orderList.value = [...orderList.value, ...res.data.list]
  total.value = res.data.total
  finish.value = false
}

// 滚动触底
const onScrolltolower = async () => {
  if (finish.value === true) {
    return
  }
  if (orderList.value.length < total.value) {
    params.value.page = params.value.page + 1
  } else {
    noMore.value = true
    return
  }
  await request()
}

const triggered = ref(false) // 设置当前下拉刷新状态，true 表示下拉刷新已经被触发，false 表示下拉刷新未被触发

const onPulling = (e: any) => {
  if (e.detail.deltaY < 50) return // 防止上滑页面也触发下拉
  triggered.value = true
}
// 自定义下拉刷新被复位
const onRestore = () => {
  triggered.value = false
}
// 自定义下拉刷新被中止
const onAbort = () => {
  console.error('onAbort')
}
// 自定义下拉刷新被触发
const onRefresh = async () => {
  orderList.value = []
  params.value = {
    ...params.value,
    page: initParams.page,
    limit: initParams.limit,
  }
  await request()
  uni.stopPullDownRefresh()
}

const tabChange = async (index: any) => {
  activeIndex.value = index
  const orderStatus = getorderStatusTabs().find((item: any, idx: number) => idx === index)
    ?.orderState as number
  params.value = {
    ...params.value,
    ...initParams,
    orderStatus,
  }
  console.log(params.value)
  orderList.value = []
  uni.stopPullDownRefresh()
  await request()
}
const swiperChange = async (event: any) => {
  activeIndex.value = event.detail.current
  const orderStatus = getorderStatusTabs().find(
    (item: any, idx: number) => idx === activeIndex.value,
  )?.orderState as number
  params.value = { ...params.value, ...initParams, orderStatus }
  orderList.value = []
  uni.stopPullDownRefresh()
  await request()
}

const orderCancelHandler = async (item: IOrder) => {
  // 模态弹窗
  uni.showModal({
    content: '确定取消订单？',
    success: async (res: any) => {
      if (res.confirm && item.orderStatus === 0) {
        await cancelOrderAPI({
          orderId: item.id as number,
          userId: getUserInfo()?.id,
          reason: '用户手动取消订单',
        })
        orderList.value = orderList.value.map((order: IOrder) => {
          if (order.id === item.id) {
            order.orderStatus = 6
          }
          return order
        })
      }
    },
  })
}

// const refundHandler = async (item: IOrder) => {
//   if (item.orderStatus === 1) {
//     await pageOrderStatusAPI({
//       id: item.id as number,
//       userId: getUserInfo()?.id,
//       orderStatus: 6,
//     })

//     orderList.value = orderList.value.map((order: IOrder) => {
//       if (order.id === item.id) {
//         order.orderStatus = 6
//       }
//       return order
//     })
//   }
// }

const payHandler = (item: IOrder) => {
  if (item.orderStatus === 0) {
    uni.navigateTo({
      url: `/pagesOrder/payment/payment?orderId=${item.id}&orderPaymentId=${item.orderPaymentId}`,
    })
  }
}

const detailOrderRequest = async (item: IOrder) => {
  const res = await aginDetailAPI({
    orderId: item.id,
  })
  setBuyMethodActiveIndex(item.eatType)
  addOrderData(res.data as IcartItem[])
  uni.navigateTo({ url: '/pagesOrder/create/create' })
}

const createOrderHandler = (item: IOrder) => {
  detailOrderRequest(item)
}

const detailOrderHandler = (item: IOrder) => {
  uni.navigateTo({ url: '/pagesOrder/detail/detail?orderId=' + item.id })
}

const storeNavigateHandler = (item: IOrder) => {
  uni.navigateTo({ url: '/pagesStore/detail/detail?id=' + item.storeId })
}

const navViewHandler = (info: IOrder) => {
  if (info.reviewId) {
    uni.navigateTo({
      url:
        '/pagesOrder/review/review?orderId=' +
        info.id +
        '&reviewId=' +
        info.reviewId +
        '&storeId=' +
        info.storeId,
    })
  } else {
    setReviewData(info.orderItemsList)
    uni.navigateTo({
      url: '/pagesOrder/review/review?orderId=' + info.id + '&storeId=' + info.storeId,
    })
  }
}

const copyTap = (tradeNo: any) => {
  // 复制到剪贴板
  uni.setClipboardData({
    data: tradeNo,
    success: () => {
      uni.showToast({
        title: '复制成功',
        icon: 'success',
        duration: 1500,
      })
    },
    fail: () => {
      uni.showToast({
        title: '复制失败',
        icon: 'error',
      })
    },
  })
}

const popup = ref<{
  open: (type?: UniHelper.UniPopupType) => void
  close: () => void
}>()
const popupName = ref<'refund'>()

const refundParams = ref({} as any)
const openRefundPopup = (name: typeof popupName.value, item: IOrder) => {
  refundParams.value = {
    orderId: item.id,
    paymentId: item.orderPaymentId,
    orderStatus: item.orderStatus,
  }
  // 修改弹出层名称
  popupName.value = name
  // 打开弹出层
  popup.value?.open()
}
</script>

<template>
  <view class="order-status">
    <!-- <view class="tabs">
      <text
        class="item"
        :class="{ active: activeIndex === index }"
        v-for="(item, index) in orderTabs"
        :key="item.title"
        @click="activeIndex = index"
      >
        {{ item.title }}
      </text>
      <view class="cursor" :style="{ left: activeIndex * 20 + '%' }"></view>
    </view> -->

    <wuc-tab
      :tab-list="orderTabs"
      :tabCur="activeIndex"
      tab-class="text-center bg-white wuc-tab fixed"
      select-class="text-blue"
      @change="tabChange"
    ></wuc-tab>

    <!-- 滑动容器 -->
    <swiper class="swiper" :current="activeIndex" @change="swiperChange">
      <!-- 滑动项 -->
      <swiper-item v-for="oitem in orderTabs" :key="oitem.orderState">
        <scroll-view
          v-if="orderList?.length"
          scroll-y
          class="order-main"
          @scrolltolower="onScrolltolower"
          :refresher-enabled="true"
          :refresher-triggered="triggered"
          :refresher-threshold="100"
          refresher-background="#F5F5F7"
          @refresherpulling="onPulling"
          @refresherrefresh="onRefresh"
          @refresherrestore="onRestore"
          @refresherabort="onAbort"
        >
          <view class="order-tip" v-if="oitem.orderState === 0">
            30分钟后，<text class="txt">待付款</text>-将自动取消定单
          </view>
          <view class="order-content" v-for="(item, index) in orderList" :key="index">
            <view class="header">
              <!-- 订单编号 -->
              <text class="title" @click="storeNavigateHandler(item)">{{ item.storeName }}</text>
              <text
                :class="orderStatusTabsClassName(item.orderStatus)"
                @click="detailOrderHandler(item)"
                >{{ orderStatusTabsName(item.orderStatus) }}</text
              >
            </view>
            <!-- <navigator
              :url="`/pagesOrder/detail/detail?id=${2}`" -->
            <view class="good-item" v-for="goodItem in item.orderItemsList" :key="goodItem.id">
              <image class="left" :src="goodItem.image" mode="scaleToFill" />
              <view class="center">
                <view class="name">{{ goodItem.goodsName }}</view>
                <view class="spec">
                  <rich-text :nodes="formateStr(goodItem)"></rich-text>
                </view>
                <view class="price-box">
                  <text class="price">¥{{ goodItem.price }}</text>
                  <text class="num">x{{ goodItem.quantity }}</text>
                </view>
              </view>
            </view>
            <view class="info">
              <view class="info-item">
                <text class="iconfont icon-wenben_o"></text>
                <text>订单编号:</text>
                <text>{{ item.tradeNo }}</text>
                <text class="iconfont icon-fuzhi_o" @click="copyTap(item.tradeNo)"></text>
              </view>
              <view class="info-item">
                <text class="iconfont icon-shijian1"></text>
                <text>下单时间:</text>
                <text>{{ item.createDate }}</text>
              </view>
              <view class="info-item">
                <text class="iconfont icon-xiuxianqu"></text>
                <text>就餐方式:</text>
                <text>{{ getBuyMethodName(item.eatType) }}</text>
              </view>
              <template v-if="item.eatType === 2">
                <view class="info-item">
                  <text class="iconfont icon-dianwei"></text>
                  <text>配送地址:</text>
                  <text>{{ item.deliveryAddress }}</text>
                </view>
                <view class="info-item">
                  <text class="iconfont icon-dianhua"></text>
                  <text>联系电话:</text>
                  <text>{{ item.deliveryPhone }}</text>
                </view>
              </template>
            </view>

            <view class="order-operation" v-if="item.orderStatus === 0">
              <text class="cancel" @click="orderCancelHandler(item)">取消订单</text>
              <text class="pay" @click="payHandler(item)">立即支付</text>
            </view>
            <view class="order-operation" v-else-if="item.orderStatus === 1">
              <view class="btn cancel">提醒发货</view>
            </view>
            <view class="order-operation" v-else-if="item.orderStatus === 2">
              <text class="cancel" @tap="openRefundPopup('refund', item)">申请退款</text>
              <!-- <view class="btn cancel">配送中</view> -->
            </view>
            <view class="order-operation" v-else-if="item.orderStatus === 4">
              <text class="cancel" @tap="openRefundPopup('refund', item)">申请退款</text>
              <!-- <view class="btn cancel">配送中</view> -->
            </view>
            <view class="order-operation" v-else-if="item.orderStatus === 6">
              <view class="btn pay" @click="createOrderHandler(item)">再次购买</view>
              <button class="btn cancel" @click="navViewHandler(item)">
                {{ item.reviewId ? '查看评价' : '去评价' }}
              </button>
              <!-- <text class="pay">查看评价</text> -->
            </view>
          </view>
        </scroll-view>
        <view v-if="!finish && orderList?.length === 0" class="no-data"><text>没有数据</text></view>
      </swiper-item>
    </swiper>

    <uni-popup ref="popup" type="bottom" background-color="#fff">
      <RefundPanel
        :orderId="refundParams.orderId"
        :paymentId="refundParams.paymentId"
        :orderStatus="refundParams.orderStatus"
        v-if="popupName === 'refund'"
        @close="popup?.close()"
        @submit="submitRefund"
      />
    </uni-popup>
  </view>
</template>

<style lang="scss">
@import '@/styles/variables.scss';
page {
  height: 100%;
  overflow: hidden;
}

.order-status {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: $background-color;

  .no-data {
    height: 100%;
  }

  .tabs {
    display: flex;
    justify-content: space-around;
    line-height: 60rpx;
    margin: 0 10rpx;
    background-color: #fff;
    box-shadow: 0 4rpx 6rpx rgba(240, 240, 240, 0.6);
    position: relative;
    z-index: 9;

    .item {
      flex: 1;
      text-align: center;
      padding: 20rpx;
      font-size: 28rpx;
      color: $font-color;
      font-weight: $font-medium-weight;

      &.active {
        color: $green-color;
      }
    }

    .cursor {
      position: absolute;
      left: 0;
      bottom: 0;
      width: 20%;
      height: 6rpx;
      padding: 0 50rpx;
      background-color: $green-color;
      /* 过渡效果 */
      transition: all 0.4s;
    }
  }

  .swiper {
    background-color: #f7f7f8;
    .order-main {
      flex: 1;
      padding-bottom: 60rpx;
      /* 针对 H5 端 */
      ::-webkit-scrollbar {
        display: none; /* 隐藏滚动条 */
      }
    }
  }
}
/* 小程序中的提示样式 */
.order-tip {
  display: flex;
  align-items: center;
  background-color: #fff9f0;
  color: #e67e22;
  font-size: 28rpx;
  line-height: 1.5;
  padding: 20rpx 30rpx;
  border-radius: 20rpx;
  margin: 20rpx;
  text-align: center;
  box-shadow: 0 6rpx 10rpx rgba(0, 0, 0, 0.05);
  .txt {
    color: #ef4444;
  }
}
.order-content {
  background-color: #fff;
  border-radius: 32rpx;
  padding: 32rpx;
  margin: 32rpx;

  /* 可选：添加图标增强提示效果 */
  // .order-tip:before {
  //   content: '⚠️'; /* 使用 Unicode 或者图片作为图标 */
  //   margin-right: 20rpx; /* 图标与文本之间留有间距，原8px */
  // }

  .header {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 32rpx;
    .title {
      color: #000000;
      font-size: $font-medium-size;
      font-weight: $font-medium-weight;
      display: flex;
      align-items: center;
      &::before {
        content: '\ebc6';
        font-family: 'iconfont' !important;
        color: #9ca3af;
        font-size: 40rpx;
        margin-right: 10rpx;
      }
    }
    .status01,
    .status02,
    .status03,
    .status04,
    .status05 {
      font-size: $font-size;
      font-weight: $font-regular-weight;
      color: $red-status-color;
      background-color: #fef2f2;
      line-height: 56rpx;
      border-radius: 28rpx;
      padding: 0 24rpx;
    }
    .status02 {
      color: #f97316;
      background-color: #fef2f2;
    }
    .status03 {
      color: #3b82f6;
      background-color: #eff6ff;
    }
    .status04 {
      color: #22c55e;
      background-color: #f0fdf4;
    }
    .status05 {
      color: #4b5563;
      background-color: #f3f4f6;
    }
  }
  .good-item {
    display: flex;
    // align-items: ;
    border-radius: $border-medium-radius;
    margin-bottom: 32rpx;
    min-height: 160rpx;

    .left {
      width: 160rpx;
      height: 160rpx;
      border-radius: $border-medium-radius;
      overflow: hidden;

      image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .center {
      flex: 1;
      margin-left: 32rpx;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      height: 100%;
      min-height: 160rpx;

      .name {
        font-size: $font-medium-size;
        color: #000;
        font-weight: $font-medium-weight;
      }

      .spec {
        font-size: $font-size;
        color: $good-font-con-color;
        font-weight: $font-regular-weight;
        margin: 10rpx 0;
      }

      .price-box {
        display: flex;
        align-items: end;
        justify-content: space-between;
        .price {
          font-size: $font-medium-size;
          color: $green-color;
          font-weight: $font-medium-weight;
        }
        .num {
          font-size: $font-medium-size;
          font-weight: $font-regular-weight;
          color: #6b7280;
        }
      }
    }
  }

  .info {
    display: flex;
    flex-direction: column;
    .info-item {
      display: flex;
      flex-direction: row;
      justify-content: left;
      margin-bottom: 20rpx;
      align-items: center;
      .icon-fuzhi_o {
        font-size: 34rpx;
        margin-left: 20rpx;
      }

      .icon-wenben_o {
        font-size: 38rpx;
        margin-right: 6rpx;
        margin-left: -6rpx;
      }

      text {
        color: $good-font-con-color;
        font-size: 28rpx;
        font-weight: $font-regular-weight;
        &.iconfont {
          color: $good-font-con-color;
          margin-right: 10rpx;
        }
        &:nth-of-type(2) {
          margin-right: 10rpx;
        }
      }
    }
  }
  .order-operation {
    gap: 20rpx;
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 84rpx;
    box-sizing: border-box;
    justify-content: flex-end;
    .btn {
      box-sizing: border-box;
    }
    .cancel {
      color: $font-color;
      line-height: 84rpx;
      border: 1px solid #ccc;
      padding: 0 32rpx;
      border-radius: 42rpx;
      font-size: $font-medium-size;
      margin: 0;
    }
    .pay {
      color: #fff;
      line-height: 84rpx;
      background-color: $green-color;
      padding: 0 32rpx;
      border-radius: 42rpx;
      font-size: $font-medium-size;
      margin: 0;
    }
  }
}

// 订单列表
.orders {
  .card {
    min-height: 100rpx;
    padding: 20rpx;
    margin: 20rpx 20rpx 0;
    border-radius: 10rpx;
    background-color: #fff;

    &:last-child {
      padding-bottom: 40rpx;
    }
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #999;
    margin-bottom: 15rpx;

    .date {
      color: #666;
      flex: 1;
    }

    .primary {
      color: #ff9240;
    }

    .icon-delete {
      line-height: 1;
      margin-left: 10rpx;
      padding-left: 10rpx;
      border-left: 1rpx solid #e3e3e3;
    }
  }

  .goods {
    display: flex;
    margin-bottom: 20rpx;

    .cover {
      width: 170rpx;
      height: 170rpx;
      margin-right: 20rpx;
      border-radius: 10rpx;
      overflow: hidden;
      position: relative;
    }

    .quantity {
      position: absolute;
      bottom: 0;
      right: 0;
      line-height: 1;
      padding: 6rpx 4rpx 6rpx 8rpx;
      font-size: 24rpx;
      color: #fff;
      border-radius: 10rpx 0 0 0;
      background-color: rgba(0, 0, 0, 0.6);
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }

    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }

    .type {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 10rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .more {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 22rpx;
      color: #333;
    }
  }

  .payment {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    line-height: 1;
    padding: 20rpx 0;
    text-align: right;
    color: #999;
    font-size: 28rpx;
    border-bottom: 1rpx solid #eee;

    .quantity {
      font-size: 24rpx;
      margin-right: 16rpx;
    }

    .amount {
      color: #444;
      margin-left: 6rpx;
    }

    .symbol {
      font-size: 20rpx;
    }
  }

  .action {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: 20rpx;

    .button {
      width: 180rpx;
      height: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 20rpx;
      border-radius: 60rpx;
      border: 1rpx solid #ccc;
      font-size: 26rpx;
      color: #444;
    }

    .secondary {
      color: #27ba9b;
      border-color: #27ba9b;
    }

    .primary {
      color: #fff;
      background-color: #27ba9b;
    }
  }

  .loading-text {
    text-align: center;
    font-size: 28rpx;
    color: #666;
    padding: 20rpx 0;
  }
}
</style>
